package controllers

import (
	"fmt"
	common2 "gin-demo/common"
	model2 "gin-demo/model"
	response2 "gin-demo/response"
	util2 "gin-demo/util"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"net/http"
)

// 注册
func UserRegister(ctx *gin.Context) {
	var requestUser model2.UserInfo
	ctx.Bind(&requestUser)
	name := requestUser.Name
	telephone := requestUser.Telephone
	password := requestUser.Password
	// 数据验证
	if len(telephone) != 11 {
		//422 Unprocessable Entity 无法处理的请求实体
		response2.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		fmt.Println(telephone, len(telephone))
		return
	}
	if len(password) < 6 {
		response2.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	// 如果名称没有传，给一个10位的随机字符串
	if len(name) == 0 {
		name = util2.RandomString(10)
	}
	// 判断手机号是否存在
	if isTelephoneExist(common2.DB, telephone) {
		response2.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户已经存在")
		return
	}
	// 创建用户
	//返回密码的hash值（对用户密码进行二次处理，防止系统管理人员利用）
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response2.Response(ctx, http.StatusInternalServerError, 500, nil, "加密错误")
		return
	}
	newUser := model2.UserInfo{
		Name:      name,
		Telephone: telephone,
		Password:  string(hashPassword),
	}
	common2.DB.Create(&newUser) // 新增记录
	// 发放token
	token, err := common2.ReleaseToken(newUser)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常"})
		return
	}
	// 返回结果
	response2.Success(ctx, gin.H{"token": token}, "注册成功")
}
func UserLogin(ctx *gin.Context) {
	var requestUser model2.UserInfo
	ctx.Bind(&requestUser)
	//name := requestUser.Name
	telephone := requestUser.Telephone
	password := requestUser.Password
	// 数据验证
	if len(telephone) != 11 {
		//422 Unprocessable Entity 无法处理的请求实体
		response2.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		fmt.Println(telephone, len(telephone))
		return
	}
	if len(password) < 6 {
		response2.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	// 依据手机号，查询用户注册的数据记录
	var user model2.UserInfo
	common2.DB.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户不存在"})
		return
	}
	// 判断密码收否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "密码错误"})
		return
	}
	// 发放token
	token, err := common2.ReleaseToken(user)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常"})
		return
	}
	// 返回结果
	response2.Success(ctx, gin.H{"token": token}, "登录成功")

}
func UserDetail(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	response2.Success(ctx, gin.H{
		"user": response2.ToUserDto(user.(model2.UserInfo))}, "响应成功")
}
func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model2.UserInfo
	db.Where("telephone=?", telephone).First(&user)
	//如果没有查询到数据，对于uint数据，默认值为：0
	if user.ID != 0 {
		return true
	}
	return false
}
